package com.reus.config;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Map;

/**
 * description: 用于创建session对象
 * copyright: Copyright (c) 2018-2021
 * company: iSysCore Tech. Co., Ltd.
 *
 * @author liuxq@isyscore.com
 * @version 1.0
 * @date 2021-10-15 17:52:24
 */
public class SessionFactory {


    private Config config;

    public SessionFactory(Config config) {
        this.config = config;
    }

    public Session createSession() {
        Connection connection = getConnection(config);
        Session session = new Session(connection);
        return session;
    }

    /**
     * description: 获取数据库链接
     *
     * @param config: 配置数据
     * @modified liuxq@isyscore.com
     * @date 2021-10-15
     * @return: java.sql.Connection
     */
    private Connection getConnection(Config config) {
        Map<String, String> sourceProp = Config.getSourceProp();
        String url = sourceProp.get("connection.url");
        String driverClass = sourceProp.get("connection.driverClass");
        String username = sourceProp.get("connection.username");
        String password = sourceProp.get("connection.password");
        try {
            Class.forName(driverClass);
            Connection connection = DriverManager.getConnection(url, username, password);
            connection.setAutoCommit(true);
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}